package controllers

import (
	"fmt"
	"net/http"
	"strconv"

	"simple-crm/models"
	"simple-crm/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type PermissionController struct {
	DB *gorm.DB
}

func NewPermissionController(db *gorm.DB) *PermissionController {
	return &PermissionController{DB: db}
}

// GetPermissions 获取所有权限（包括分组和具体权限）
func (pc *PermissionController) GetPermissions(c *gin.Context) {
	var permissions []models.Permission

	// 查询所有权限，按PID和排序字段排序
	result := pc.DB.Order("pid ASC, sort ASC, id ASC").Find(&permissions)
	if result.Error != nil {
		utils.Error(c, http.StatusInternalServerError, "获取权限列表失败")
		return
	}

	utils.Success(c, gin.H{
		"permissions": permissions,
		"total":       len(permissions),
	})
}

// GetPermission 获取单个权限详情
func (pc *PermissionController) GetPermission(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		utils.Error(c, http.StatusBadRequest, "无效的权限ID")
		return
	}

	var permission models.Permission
	result := pc.DB.First(&permission, id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			utils.Error(c, http.StatusNotFound, "权限不存在")
		} else {
			utils.Error(c, http.StatusInternalServerError, "获取权限详情失败")
		}
		return
	}

	utils.Success(c, permission)
}

// CreatePermission 创建权限（分组或具体权限）
func (pc *PermissionController) CreatePermission(c *gin.Context) {
	var req struct {
		PID         uint   `json:"pid"`
		Name        string `json:"name" binding:"required"`
		DisplayName string `json:"display_name" binding:"required"`
		Resource    string `json:"resource"`
		Action      string `json:"action"`
		Description string `json:"description"`
		Sort        int    `json:"sort"`
		IsGroup     bool   `json:"is_group"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "请求参数错误",
			"message": err.Error(),
		})
		return
	}

	// 验证父级权限是否存在（如果PID不为0）
	if req.PID != 0 {
		var parent models.Permission
		result := pc.DB.First(&parent, req.PID)
		if result.Error != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "父级权限不存在"})
			return
		}
		// 确保父级是权限分组
		if !parent.IsGroup {
			c.JSON(http.StatusBadRequest, gin.H{"error": "父级必须是权限分组"})
			return
		}
	}

	// 检查权限名称是否重复
	var existingPermission models.Permission
	result := pc.DB.Where("name = ?", req.Name).First(&existingPermission)
	if result.Error == nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "权限名称已存在"})
		return
	}

	// 如果是具体权限，验证资源和操作字段
	if !req.IsGroup {
		if req.Resource == "" || req.Action == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "具体权限必须指定资源和操作"})
			return
		}
	}

	// 创建权限
	permission := models.Permission{
		PID:         req.PID,
		Name:        req.Name,
		DisplayName: req.DisplayName,
		Resource:    req.Resource,
		Action:      req.Action,
		Description: req.Description,
		Sort:        req.Sort,
		IsGroup:     req.IsGroup,
	}

	result = pc.DB.Create(&permission)
	if result.Error != nil {
		utils.Error(c, http.StatusInternalServerError, "创建权限失败")
		return
	}

	utils.SuccessWithMessage(c, "权限创建成功", permission)
}

// UpdatePermission 更新权限
func (pc *PermissionController) UpdatePermission(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的权限ID"})
		return
	}

	var req struct {
		PID         uint   `json:"pid"`
		Name        string `json:"name" binding:"required"`
		DisplayName string `json:"display_name" binding:"required"`
		Resource    string `json:"resource"`
		Action      string `json:"action"`
		Description string `json:"description"`
		Sort        int    `json:"sort"`
		IsGroup     bool   `json:"is_group"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "请求参数错误",
			"message": err.Error(),
		})
		return
	}

	// 查找要更新的权限
	var permission models.Permission
	result := pc.DB.First(&permission, id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "权限不存在"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "查找权限失败",
				"message": result.Error.Error(),
			})
		}
		return
	}

	// 验证父级权限是否存在（如果PID不为0）
	if req.PID != 0 {
		var parent models.Permission
		result := pc.DB.First(&parent, req.PID)
		if result.Error != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "父级权限不存在"})
			return
		}
		// 确保父级是权限分组
		if !parent.IsGroup {
			c.JSON(http.StatusBadRequest, gin.H{"error": "父级必须是权限分组"})
			return
		}
		// 防止循环引用
		if parent.ID == uint(id) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "不能将权限设置为自己的子权限"})
			return
		}
	}

	// 检查权限名称是否重复（排除自己）
	var existingPermission models.Permission
	result = pc.DB.Where("name = ? AND id != ?", req.Name, id).First(&existingPermission)
	if result.Error == nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "权限名称已存在"})
		return
	}

	// 如果是具体权限，验证资源和操作字段
	if !req.IsGroup {
		if req.Resource == "" || req.Action == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "具体权限必须指定资源和操作"})
			return
		}
	}

	// 如果从分组改为具体权限，检查是否有子权限
	if permission.IsGroup && !req.IsGroup {
		var childCount int64
		pc.DB.Model(&models.Permission{}).Where("pid = ?", id).Count(&childCount)
		if childCount > 0 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "该权限分组下还有子权限，无法转换为具体权限"})
			return
		}
	}

	// 更新权限
	permission.PID = req.PID
	permission.Name = req.Name
	permission.DisplayName = req.DisplayName
	permission.Resource = req.Resource
	permission.Action = req.Action
	permission.Description = req.Description
	permission.Sort = req.Sort
	permission.IsGroup = req.IsGroup

	result = pc.DB.Save(&permission)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "更新权限失败",
			"message": result.Error.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "权限更新成功",
		"data":    permission,
	})
}

// DeletePermission 删除权限
func (pc *PermissionController) DeletePermission(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的权限ID"})
		return
	}

	// 查找要删除的权限
	var permission models.Permission
	result := pc.DB.First(&permission, id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": "权限不存在"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "查找权限失败",
				"message": result.Error.Error(),
			})
		}
		return
	}

	// 如果是权限分组，检查是否有子权限
	if permission.IsGroup {
		var childPermissions []models.Permission
		result := pc.DB.Where("pid = ?", id).Find(&childPermissions)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "检查子权限失败",
				"message": result.Error.Error(),
			})
			return
		}

		// 级联删除所有子权限
		if len(childPermissions) > 0 {
			result = pc.DB.Where("pid = ?", id).Delete(&models.Permission{})
			if result.Error != nil {
				c.JSON(http.StatusInternalServerError, gin.H{
					"error":   "删除子权限失败",
					"message": result.Error.Error(),
				})
				return
			}
		}
	}

	// 删除权限本身
	result = pc.DB.Delete(&permission)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "删除权限失败",
			"message": result.Error.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "权限删除成功",
	})
}

// GetPermissionStats 获取权限统计信息
func (pc *PermissionController) GetPermissionStats(c *gin.Context) {
	var totalCount int64
	var groupCount int64
	var permissionCount int64

	// 统计总数
	pc.DB.Model(&models.Permission{}).Count(&totalCount)
	// 统计分组数
	pc.DB.Model(&models.Permission{}).Where("is_group = ?", true).Count(&groupCount)
	// 统计具体权限数
	pc.DB.Model(&models.Permission{}).Where("is_group = ?", false).Count(&permissionCount)

	utils.Success(c, gin.H{
		"total":       totalCount,
		"groups":      groupCount,
		"permissions": permissionCount,
	})
}

// GetPermissionResources 获取权限资源列表
func (pc *PermissionController) GetPermissionResources(c *gin.Context) {
	var resources []string
	pc.DB.Model(&models.Permission{}).Where("resource != '' AND resource IS NOT NULL").Distinct("resource").Pluck("resource", &resources)

	utils.Success(c, resources)
}

// BatchDeletePermissions 批量删除权限
func (pc *PermissionController) BatchDeletePermissions(c *gin.Context) {
	var req struct {
		IDs []uint `json:"ids" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "请求参数错误",
			"message": err.Error(),
		})
		return
	}

	if len(req.IDs) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请选择要删除的权限"})
		return
	}

	// 检查是否有权限分组包含子权限
	for _, id := range req.IDs {
		var permission models.Permission
		result := pc.DB.First(&permission, id)
		if result.Error != nil {
			continue
		}

		if permission.IsGroup {
			var childCount int64
			pc.DB.Model(&models.Permission{}).Where("pid = ?", permission.ID).Count(&childCount)
			if childCount > 0 {
				c.JSON(http.StatusBadRequest, gin.H{
					"error": fmt.Sprintf("权限分组 '%s' 包含子权限，无法删除", permission.DisplayName),
				})
				return
			}
		}
	}

	// 批量删除
	result := pc.DB.Delete(&models.Permission{}, req.IDs)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "批量删除权限失败",
			"message": result.Error.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success":       true,
		"message":       fmt.Sprintf("成功删除 %d 个权限", result.RowsAffected),
		"deleted_count": result.RowsAffected,
	})
}

// GetPermissionTree 获取权限树结构
func (pc *PermissionController) GetPermissionTree(c *gin.Context) {
	var permissions []models.Permission

	// 查询所有权限，按PID和排序字段排序
	result := pc.DB.Order("pid ASC, sort ASC, id ASC").Find(&permissions)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "获取权限列表失败",
			"message": result.Error.Error(),
		})
		return
	}

	// 构建树结构
	tree := buildPermissionTree(permissions, 0)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    tree,
		"total":   len(tree),
	})
}

// PermissionsIndex 权限管理页面
func (pc *PermissionController) PermissionsIndex(c *gin.Context) {
	c.HTML(http.StatusOK, "permissions/index.html", gin.H{
		"title": "权限管理",
		"user":  c.MustGet("user"),
		"CurrentPage": "permissions",
	})
}

// PermissionCreatePage 权限创建页面
func (pc *PermissionController) PermissionCreatePage(c *gin.Context) {
	c.HTML(http.StatusOK, "permissions/create.html", gin.H{
		"title": "新增权限",
		"user":  c.MustGet("user"),
		"CurrentPage": "permission-create",
	})
}

// PermissionEditPage 权限编辑页面
func (pc *PermissionController) PermissionEditPage(c *gin.Context) {
	c.HTML(http.StatusOK, "permissions/edit.html", gin.H{
		"title": "编辑权限",
		"user":  c.MustGet("user"),
		"id":    c.Param("id"),
		"CurrentPage": "permission-edit",
	})
}

// PermissionDetailPage 权限详情页面
func (pc *PermissionController) PermissionDetailPage(c *gin.Context) {
	c.HTML(http.StatusOK, "permissions/detail.html", gin.H{
		"title": "权限详情",
		"user":  c.MustGet("user"),
		"id":    c.Param("id"),
		"CurrentPage": "permission-detail",
	})
}

// buildPermissionTree 递归构建权限树
func buildPermissionTree(permissions []models.Permission, parentID uint) []map[string]interface{} {
	var tree []map[string]interface{}

	for _, permission := range permissions {
		if permission.PID == parentID {
			node := map[string]interface{}{
				"id":           permission.ID,
				"pid":          permission.PID,
				"name":         permission.Name,
				"display_name": permission.DisplayName,
				"resource":     permission.Resource,
				"action":       permission.Action,
				"description":  permission.Description,
				"sort":         permission.Sort,
				"is_group":     permission.IsGroup,
				"created_at":   permission.CreatedAt,
				"updated_at":   permission.UpdatedAt,
			}

			// 递归获取子权限
			children := buildPermissionTree(permissions, permission.ID)
			if len(children) > 0 {
				node["children"] = children
			}

			tree = append(tree, node)
		}
	}

	return tree
}
